package com.elvin.usingservice;

import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.os.Build;

public class MainActivity extends Activity implements OnClickListener, ServiceConnection {

	private Button btnStartService, btnStopService;
	private Button btnBindService, btnUnBindService;
	private Button btnGetCurrentNum;
	private Intent serviceIntent;
	
	private EchoService echoService = null;
	
	private final String TAG = "MainActivity";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		serviceIntent = new Intent(this, EchoService.class);

		btnStartService = (Button)findViewById(R.id.btnStartService);
		btnStopService = (Button)findViewById(R.id.btnStopService);
		btnBindService = (Button)findViewById(R.id.btnBindService);
		btnUnBindService = (Button)findViewById(R.id.btnUnBindService);
		btnGetCurrentNum = (Button)findViewById(R.id.btnGetCurrentNum);
		
		btnStartService.setOnClickListener(this);
		btnStopService.setOnClickListener(this);
		btnBindService.setOnClickListener(this);
		btnUnBindService.setOnClickListener(this);
		btnGetCurrentNum.setOnClickListener(this);
		
		
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
		switch (v.getId()) {
		
		case R.id.btnStartService:
			startService(serviceIntent);
			break;
		case R.id.btnStopService:
			stopService(serviceIntent);
			break;
		case R.id.btnBindService:
			bindService(serviceIntent, this, Context.BIND_AUTO_CREATE);
			break;
		case R.id.btnUnBindService:
			unbindService(this);
			echoService = null;
			break;
		case R.id.btnGetCurrentNum:
			if(echoService != null){
				Log.i(TAG,"-->当前服务中的数字是:"+echoService.getCurrentNum());
			}
			break;

		default:
			break;
		}
		
	}

	//Service成功bind会执行这个方法
	@Override
	public void onServiceConnected(ComponentName name, IBinder binder) {
		// TODO Auto-generated method stub
		Log.i(TAG, "-->onServiceConnected");
		
		//这里的binder就是从Service返回的EchoServiceBinder对象
		echoService = ((EchoService.EchoServiceBinder)binder).getService();
		
	}

	//Service崩溃的时候触发（不常用）
	@Override
	public void onServiceDisconnected(ComponentName name) {
		// TODO Auto-generated method stub
		
	}
	
	

}
